<template>
  <el-drawer
      :model-value="drawerVisible"
      title="添加商标"
      :before-close="handleClose"
      size="50%"
      direction="rtl"
      class="demo-drawer"
  >
    <div class="demo-drawer__content">
      <el-form :model="form" label-width="80px">
        <!-- Brand Name -->
        <el-form-item label="品牌名称">
          <el-input v-model="form.brandName" clearable autocomplete="off"/>
        </el-form-item>
        <!-- Brand Website -->
        <el-form-item label="官方网站">
          <el-input v-model="form.brandNet" clearable autocomplete="off"/>
        </el-form-item>
        <!-- Upload Brand Logo -->
        <el-form-item label="上传品牌图片">
          <upload ref="uploadComponent" @upload-success="handleUploadSuccess"></upload>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="startSubmitProcess">添加</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script lang="ts" setup>
import {reactive, ref, watch} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import upload from '@/components/upload.vue';
import { addBrand } from '@/api/brand';
import {headImgStore} from '@/store/tokenStore';

// 定义props
const props = defineProps({
  drawerVisible: Boolean,
});

// 定义emits
const emit = defineEmits(['update:drawerVisible', 'formSubmitted']);

// 表单数据对象
const form = reactive({
  brandName: "",
  brandNet: "",
  brandImg: ""
});

// 引用子组件实例
const uploadComponent = ref(null);

// 获取头部图片存储
const headImg = headImgStore();

// 方法：开始提交过程，先尝试上传图片
// 定义上传图片的Promise
const startSubmitProcess = async () => {
  try {
    if (uploadComponent.value) {
      // 使用Promise等待上传完成
      const uploadPromise = new Promise<void>((resolve, reject) => {
        let unwatch: (() => void) | null = null; // 提前声明unwatch
        unwatch = watch(
          () => headImg.headImg,
          (newVal) => {
            if (newVal) {
              if (unwatch) unwatch(); // 确保unwatch已初始化
              resolve();
            }
          },
          { immediate: true }
        );

        // 调用子组件的manualUpload方法并立即启动上传
        uploadComponent.value.manualUpload();
      });

      await uploadPromise; // 等待上传完成
    }
    // 准备发送给后端的数据
    const formData = {
      ...form,
      brandImg: headImg.headImg, // 防止为空时引发问题
    };

    console.log(formData)
    // 发送请求添加商标
    await addBrand(formData);
    ElMessage.success("商标添加成功");
    emit("formSubmitted");
    emit("update:drawerVisible", false);
    resetForm();
  } catch (error) {
    ElMessage.error("商标添加失败，请重试");
    console.error(error); // 记录错误信息，方便调试
  }
};

// 图片上传成功的回调方法
const handleUploadSuccess = (url) => {
  form.brandImg = url;
};

// 关闭抽屉的方法
const handleClose = (done) => {
  ElMessageBox.confirm('确认退出填写？退出后将清空填写内容', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    emit('update:drawerVisible', false);
    resetForm();
  }).catch(() => {
    // 用户选择取消关闭抽屉
  });
};

// 重置表单的方法
const resetForm = () => {
  Object.assign(form, {
    brandName: "",
    brandNet: "",
    brandImg: ""
  });
  headImg.clearHeadImg();
};

// 取消操作的方法
const cancelForm = () => {
  emit('update:drawerVisible', false);
  resetForm();
};
</script>
<style scoped>
.demo-drawer__content {
  padding: 20px;
}

.demo-drawer__footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}
</style>